package com.tadpole.music.presenter.home;

import com.tadpole.music.bean.home.BannerBean;
import com.tadpole.music.callback.BaseCallback;
import com.tadpole.music.config.UrlConfig;
import com.tadpole.music.iView.home.BannerIView;
import com.tadpole.music.model.base.DataModel;
import com.tadpole.music.model.base.ModelToken;
import com.tadpole.music.presenter.base.BasePresenter;
import com.tadpole.music.utils.JsonParseUtil;
import com.tadpole.music.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 获取首页轮播图
 * Created By 孙岩
 * on 2020/9/18
 */
public class BannerPresenter extends BasePresenter<BannerIView> {
    @SuppressWarnings("unchecked")
    public void getBanner(){
        if(isViewAttached()){
            String url = UrlConfig.homeBanner;
            DataModel.request(ModelToken.GET_REQUEST)
                    .url(url)
                    .execute(new BaseCallback<String>() {
                        @Override
                        public void onSuccess(String data) {
                            try {
                                JSONObject obj = new JSONObject(data);
                                if(obj.getInt("code")==200){
                                    JSONArray array = new JSONArray(obj.getString("data"));
                                    List<BannerBean.DataBean> list = new ArrayList<>();
                                    for(int i=0;i<array.length();i++){
                                        JSONObject object = new JSONObject(array.get(i).toString());
                                        BannerBean.DataBean bean = new BannerBean.DataBean(
                                                JsonParseUtil.getStr(object,"thumb"),
                                                JsonParseUtil.getStr(object,"link_url")
                                        );
                                        list.add(bean);
                                    }
                                    getView().showBanner(list);
                                }else{
                                    ToastUtils.show(obj.getString("msg"));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(String msg) {
                            getView().showErr();
                            getView().stopRefresh();
                        }

                        @Override
                        public void onComplete() {
                            getView().stopRefresh();
                        }

                        @Override
                        public void onBefore() {

                        }
                    });
        }
    }
}
